package br.com.ianalise.gui;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import br.com.ianalise.negocio.excecoes.IAnaliseException;
import br.com.ianalise.negocio.fachada.Fachada;
import br.com.ianalise.negocio.pojo.ConfigRede;
import br.com.ianalise.outros.ThreadServer;
import br.com.ianalise.outros.pegarIP;

public class TelaPrincipal {

	private JFrame frmIanlise;
	private Thread threadServer;
	private ConfigRede configRede;
	private JLabel lblTerminalDados;
	private JLabel lblServidorIP;
	//private Dimension tela;
	private static String titulo = "iAnálise 2012";
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					TelaPrincipal window = new TelaPrincipal();
					window.frmIanlise.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 * @throws IAnaliseException 
	 * @throws Exception 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws ClassNotFoundException 
	 */
	public TelaPrincipal() throws IAnaliseException {
		try {
			String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
			UIManager.setLookAndFeel(lookAndFeel);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new IAnaliseException(e.toString());
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new IAnaliseException(e.toString());
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new IAnaliseException(e.toString());
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new IAnaliseException(e.toString());
		}
			
		initialize();
		
		configRede = Fachada.getInstancia().consultarConfig();
		
		if(configRede.getTipoNo().equals("servidor")) {
			threadServer = ThreadServer.getInstancia(configRede.getPorta());
			threadServer.start();
			lblTerminalDados.setText(pegarIP.localhost()+" ("+configRede.getTipoNo()+")");
			lblServidorIP.setText(pegarIP.localhost());
		} else {
			lblTerminalDados.setText(pegarIP.localhost()+" ("+configRede.getTipoNo()+")");
			lblServidorIP.setText(configRede.getIpServidor());
		}
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		//tela = Toolkit.getDefaultToolkit().getScreenSize();  
		
		frmIanlise = new JFrame();
		frmIanlise.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				int opcao = JOptionPane.showOptionDialog(null,
                        "Deseja realmente fechar o "+titulo+"?",
                        titulo, JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null,
                        null, null);
				
				if (opcao == 0) { // se desejar cadastrar
					System.exit(0);
				}
			}
		});
		frmIanlise.setTitle(titulo);
		frmIanlise.setBounds(100, 100, 800, 640);
		frmIanlise.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		frmIanlise.setExtendedState(JFrame.MAXIMIZED_BOTH);  
		frmIanlise.setMinimumSize(new Dimension(400,500));
		
		JMenuBar menuBar = new JMenuBar();
		frmIanlise.setJMenuBar(menuBar);
		
		JMenu mnArquivo = new JMenu("Arquivo");
		mnArquivo.setMnemonic(65);
		menuBar.add(mnArquivo);
		
		JMenuItem mntmBackupDoBd = new JMenuItem("Backup do BD");
		mntmBackupDoBd.setMnemonic(66);
		mnArquivo.add(mntmBackupDoBd);
		
		JMenuItem mntmSair = new JMenuItem("Sair");
		mntmSair.setMnemonic(83);
		mntmSair.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int opcao = JOptionPane.showOptionDialog(null,
                        "Deseja realmente fechar o "+titulo+"?",
                        titulo, JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null,
                        null, null);
				
				if (opcao == 0) { // se desejar cadastrar
					System.exit(0);
				}
			}
		});
		mntmSair.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
		mnArquivo.add(mntmSair);
		
		JMenu mnCadastrar = new JMenu("Cadastrar");
		mnCadastrar.setMnemonic(67);
		menuBar.add(mnCadastrar);
		
		JMenuItem mntmPaciente = new JMenuItem("Paciente");
		mntmPaciente.setMnemonic(80);
		mntmPaciente.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
		mntmPaciente.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				CadastrarPaciente cadastrarPaciente;
				
				try {
					cadastrarPaciente = new CadastrarPaciente(titulo,
							"Cadastrar Paciente");
					cadastrarPaciente.setVisible(true);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					try {
						throw new IAnaliseException(e.toString());
					} catch (IAnaliseException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		mnCadastrar.add(mntmPaciente);
		
		JMenuItem mntmExame = new JMenuItem("Exame");
		mntmExame.setMnemonic(69);
		mnCadastrar.add(mntmExame);
		
		JMenu mnRelatrios = new JMenu("Relatórios");
		mnRelatrios.setMnemonic(82);
		menuBar.add(mnRelatrios);
		
		JMenu mnPreferncias = new JMenu("Preferências");
		mnPreferncias.setMnemonic(80);
		menuBar.add(mnPreferncias);
		
		JMenuItem mntmConfiguracoes = new JMenuItem("Configurações de Rede");
		mntmConfiguracoes.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.ALT_MASK));
		mntmConfiguracoes.setMnemonic(82);
		mntmConfiguracoes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ConfiguracoesRede configuracoes;
				try {
					configuracoes = new ConfiguracoesRede(titulo, "Configurações de Rede");
					configuracoes.setVisible(true);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					try {
						throw new IAnaliseException(e1.toString());
					} catch (IAnaliseException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
				}
			}
		});
		mnPreferncias.add(mntmConfiguracoes);
		frmIanlise.getContentPane().setLayout(null);
		
		JLabel lblLaboratrio = new JLabel("Laboratório:");
		lblLaboratrio.setBounds(10, 258, 94, 15);
		frmIanlise.getContentPane().add(lblLaboratrio);
		
		JLabel lblUsuário = new JLabel("Usuário:");
		lblUsuário.setBounds(10, 285, 70, 15);
		frmIanlise.getContentPane().add(lblUsuário);
		
		JLabel lblTerminal = new JLabel("Terminal:");
		lblTerminal.setBounds(10, 204, 70, 15);
		frmIanlise.getContentPane().add(lblTerminal);
		
		lblTerminalDados = new JLabel("");
		lblTerminalDados.setBounds(79, 204, 282, 15);
		frmIanlise.getContentPane().add(lblTerminalDados);
		
		JLabel lblServidor = new JLabel("Servidor:");
		lblServidor.setBounds(10, 231, 70, 15);
		frmIanlise.getContentPane().add(lblServidor);
		
		lblServidorIP = new JLabel("");
		lblServidorIP.setBounds(79, 231, 282, 15);
		frmIanlise.getContentPane().add(lblServidorIP);
		
		JLabel lblLogo = new JLabel();
		lblLogo.setIcon(new ImageIcon(TelaPrincipal.class.getResource("/br/com/ianalise/imagens/fundo/logo_ianalise.png")));
		lblLogo.setBounds(10, 10, 299, 182);
		//lblLogo.setHorizontalAlignment(SwingConstants.CENTER);
		frmIanlise.getContentPane().add(lblLogo);
		
		JLabel lblFundo = new JLabel();
		lblFundo.setIcon(new ImageIcon(TelaPrincipal.class.getResource("/br/com/ianalise/imagens/fundo/fundo.jpg")));
		lblFundo.setBounds(0, 0, 1500, 900);
		frmIanlise.getContentPane().add(lblFundo);
	}
}
